package xyz.itpath.gen.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import xyz.itpath.gen.autoconfigure.ProjectConfiguration;
import xyz.itpath.gen.dto.ClassField;
import xyz.itpath.gen.dto.Column;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhaom
 * @date 2021/9/22 - 14:54
 */
@Component
public class TypeMapUtils {


    private final ProjectConfiguration projectConfiguration;

    private static final Map<String, String> TYPE_MAP = new HashMap<>();

    private static final Map<String, String> IMPORT_NAME_MAP = new HashMap<>();

    static {
        IMPORT_NAME_MAP.put("BigDecimal", BigDecimal.class.getName());
        IMPORT_NAME_MAP.put("Date", Date.class.getName());
    }

    public TypeMapUtils(ProjectConfiguration projectConfiguration) {
        this.projectConfiguration = projectConfiguration;
    }

    private void initTypeMap(){
        ClassPathResource resource = new ClassPathResource("type-map.json");
        try {
            BufferedReader fileReader = new BufferedReader(new FileReader(resource.getFile()));
            String str;
            StringBuilder sb = new StringBuilder();
            while ((str = fileReader.readLine()) != null) {
                sb.append(str);
            }
            JSONObject jsonObject = JSONObject.parseObject(sb.toString());
            JSONObject currDb = jsonObject.getObject(projectConfiguration.getTypeDb(), JSONObject.class);
            currDb.keySet().forEach(item -> TYPE_MAP.put(item, currDb.getString(item)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将表属性转为类属性
     */
    public List<ClassField> convertColumnToField(List<Column> columns) {
        if (TYPE_MAP.isEmpty()){
            this.initTypeMap();
        }
        return columns.stream().map(column -> {
            ClassField classField = new ClassField();
            classField.setFieldName(StringUtils.underlineToCamel(column.getColumnName()));
            classField.setUpperCamelFieldName(StringUtils.underlineToUpperCamel(column.getColumnName()));
            classField.setDataType(TYPE_MAP.get(column.getDataType()));
            classField.setComment(column.getColumnComment());
            return classField;
        }).collect(Collectors.toList());
    }

    /**
     * 获取导包字符串
     */
    public Set<String> getImportString(List<ClassField> classFields) {
        return classFields.stream()
                .map(item -> IMPORT_NAME_MAP.getOrDefault(item.getDataType(), ""))
                .filter(item -> !StringUtils.isBlank(item))
                .collect(Collectors.toSet());
    }
}
